<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Env;
use think\Db;
use app\admin\model\Admin;
use app\admin\model\AdminOauth;
use app\admin\model\AdminGroup;
use app\admin\model\AdminRule;
use think\Container;

class Thinkadx extends Command
{
    protected function configure() {
        // 指令配置
        $this->setName('thinkadx')
        ->addOption('init', null, Option::VALUE_REQUIRED, 'init action')
        ->addOption('action', null, Option::VALUE_REQUIRED, 'action name')
        ->setDescription('thinkadx');
    }

    protected function execute(Input $input, Output $output)
    {
        $result = '';
        if($input->hasOption('init')) {
            $initType = $input->getOption('init');
            switch($initType) {
                case 'mysql' : 
                        // 检测是否可以导入
                        try {
                            if(Admin::count() > 0) {
                                throw new \think\Exception('admin init fail', 10006);
                            }
                        } catch(\think\exception\PDOException $e) {
                            // echo 'ok';
                        }   
                        
                        // 导入mysql
                        $myfile = fopen('mysql.sql', 'r');
                        $sqlString = fread($myfile,filesize("mysql.sql"));
                        fclose($myfile);
                        $sqlArr = explode(';', $sqlString);
                        //执行sql语句
                        array_pop($sqlArr);
                        foreach ($sqlArr as $_value) {
                            Db::execute($_value.';');
                        }
                        $output->writeln('data write success...');

                        // 创建系统资源
                        $output->writeln('create resources ...');
                        $this->createDefaultIcon($output);
                        $output->writeln('init success!!!');
                    break;
            }
        } else if($input->hasOption('action')) {
            // 操作
            $initType = $input->getOption('action');
            switch($initType) {
                case 'empty_expired_cache' : 
                        // 清空过期缓存
                        $path = Container::get('app')->getRuntimePath() . 'cache' . DIRECTORY_SEPARATOR;
                        $files = (array) glob($path . (config('cache.default.prefix') ? config('cache.default.prefix') . DIRECTORY_SEPARATOR : '') . '*');
                        foreach ($files as $path) {
                            if (is_dir($path)) {
                                $matches = glob($path . DIRECTORY_SEPARATOR . '*.php');
                                array_map('del_expired_file_cache', $matches);
                                // 文件夹为空则删除
                                if(empty(array_diff(scandir($path),array('..','.')))) {
                                    rmdir($path);
                                }
                            } else {
                                del_expired_file_cache($path);
                            }
                        }
                        $output->writeln('action success');
                    break;
            }
        }

    	// 指令输出
    }

    protected function createDefaultIcon($output) {
        $systemDefaultIconDir = Env::get('root_path') . 'public/uploads/system_default_icon/';
        if(!is_dir($systemDefaultIconDir)) {
            mkdir($systemDefaultIconDir, '0744', true);
        }

        // 默认头像
        $defaultUserAvatarbase = '';
        $file = $this->createBaseFile('avatar', $defaultUserAvatarbase, $systemDefaultIconDir);

        // 菜单-系统设置
        $defaultUserAvatarbase = '';
        $file = $this->createBaseFile('system_setup', $defaultUserAvatarbase, $systemDefaultIconDir);

        // 菜单-管理员管理
        $defaultUserAvatarbase = '';
        $file = $this->createBaseFile('admin_manage', $defaultUserAvatarbase, $systemDefaultIconDir);

        $output->writeln($systemDefaultIconDir);
    }


    /**
     * 创建文件
     * @param string $name 文件名
     * @param string $content 文件内容
     * @param string $path 文件路径
     * @return void
     */
    protected function createBaseFile($name, $content, $path) {
        //正则匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result)) {
            $type = $result[2];  //获取图片格式
            $new_file = $path . $name . ".{$type}";
            file_put_contents($new_file, base64_decode(str_replace($result[1], '', $content)));
        }
    }

}
